package com.be.beadmin.system.impl.ProjectSysServiceImpl;

import com.be.beadmin.logging.dto.input.LogDto;
import com.be.beadmin.logging.service.LogService;
import com.be.beadmin.service.util.QueryInfo;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.be.beadmin.basicData.entity.Customer;
import com.be.beadmin.basicData.entity.MaterialInfo;
import com.be.beadmin.basicData.repository.CustomerRepository;
import com.be.beadmin.basicData.service.MaterialInfoService;
import com.be.beadmin.product.entity.ProductOrderInfo;
import com.be.beadmin.product.entity.PurchaseOrderInfo;
import com.be.beadmin.product.service.ErrorReportService;
import com.be.beadmin.product.service.ProductOrderInfoService;
import com.be.beadmin.product.service.PurchaseOrderInfoService;
import com.be.beadmin.system.util.ApiUrlProperties;
import com.be.beadmin.project.entity.Info;
import com.be.beadmin.system.service.AuthorizeService;
import com.be.beadmin.project.service.InfoService;
import com.be.beadmin.service.util.AuthorizeCode;
import io.micrometer.core.instrument.util.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import com.alibaba.fastjson.JSON;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AuthorizeServiceImpl implements AuthorizeService {
    RestTemplate restTemplate = new RestTemplate();

    @Resource
    private InfoService infoService;

    @Resource
    private CustomerRepository customerRepository;

    @Resource
    private ApiUrlProperties apiUrlProperties;

    @Resource
    private ProductOrderInfoService productOrderInfoService;

    @Resource
    private MaterialInfoService materialInfoService;

    @Resource
    private PurchaseOrderInfoService purchaseOrderInfoService;

//    @Autowired
//    public AuthorizeServiceImpl(ApiUrlProperties apiUrlProperties) {
//        this.apiUrlProperties  = apiUrlProperties;
//    }

    @Resource
    private ErrorReportService errorReportService;

    @Resource
    private LogService logService;

    public static String EXCEPTION_PRIORITY = "2";

    public static String HANDING_MAN = "admin2";

    public static List<String> MATERIAL_PROPERTY = Arrays.asList("产成品", "生产加工");

    public static String TOKEN;
    public static String ResponseString=">>>>>:<200,{\"ResCode\":0,\"Success\":true,\"ResMsg\":\"授权码有效期为3分钟。\",\"Data\":\"cc0b66567cfc401ba7b103cdc87aa145\"},{Cache-Control=[no-cache], Pragma=[no-cache], Content-Type=[application/json; charset=utf-8], Expires=[-1], Set-Cookie=[.ASPXANONYMOUS=RAPzBNR03AEkAAAANjU1YjJjNTItNTQ4MS00OGY2LWFlMTgtNGZkZDEzZmY4ODNm0; expires=Wed, 24-Dec-2025 12:51:27 GMT; path=/; HttpOnly, ASP.NET_SessionId=3q35wf0iq2chbejtzurgld4d; path=/; HttpOnly; SameSite=Lax], X-Content-Type-Options=[nosniff], X-XSS-Protection=[1], Strict-Transport-Security=[max-age=31536000; includeSubDomains], X-Frame-Options=[SAMEORIGIN], X-Powered-By=[ASP.NET], Date=[Tue, 30 Jan 2024 02:11:27 GMT], Content-Length=[113]}>\n";
    public String getTOKEN(){
        return TOKEN;
    }

//    public static String teststr="{ \"ResCode\": 0,\"Success\": true,\"ResMsg\": null, \"Data\": [{\"materialcode\": \"GC1823999CP-0001\",\"materialname\": \"西门子测试料品1\"} ]}";
    @Override
    public ResponseEntity<Map> executeHttpRequest(String token, String sqlString, ApiUrlProperties apiUrlProperties, RestTemplate restTemplate) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("token", token);
        QueryInfo queryInfo=new QueryInfo();
        queryInfo.setSqlString(sqlString);
        HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(queryInfo), headers);
        String url = String.format("%s/QueryCommon/QueryInfoBySql", apiUrlProperties.getApiUrl_prefix());
        System.out.println("配置:"+url);
        ResponseEntity<Map> ResponseEntity=restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class);
        System.out.println("响应:"+ResponseEntity.getBody());

        LogDto logDto = new LogDto();
        String json = String.format("{\"token\":\"%s\", \"sqlString\":\"%s\", \"apiUrlProperties\":\"%s\", \"restTemplate\":\"%s\"}",
                token, sqlString, apiUrlProperties, restTemplate);
        logDto.setParams(json);
        logDto.setDescription("executeHttpRequest");
        logDto.setLogType("Interface");
        logService.addLog(logDto);
        return  ResponseEntity;
    }

    @Override
    public ResponseEntity<Map> executeIssueRequest(String token, String sqlString, ApiUrlProperties apiUrlProperties, RestTemplate restTemplate) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("token", token);
        HttpEntity<String> requestEntity = new HttpEntity<>(sqlString, headers);
        String url = String.format("%s/IssueDoc/Create", apiUrlProperties.getApiUrl_prefix());
        System.out.println("配置:"+url);

        LogDto logDto = new LogDto();
        String json = String.format("{\"token\":\"%s\", \"sqlString\":\"%s\", \"apiUrlProperties\":\"%s\", \"restTemplate\":\"%s\"}",
                token, sqlString, apiUrlProperties, restTemplate);
        logDto.setParams(json);
        logDto.setDescription("executeIssueRequest");
        logDto.setLogType("Interface");
        logService.addLog(logDto);

        return restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class);
    }

    @Override
    public ResponseEntity<Map> executeRcvRptRequest(String token, String sqlString, ApiUrlProperties apiUrlProperties, RestTemplate restTemplate) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("token", token);
        HttpEntity<String> requestEntity = new HttpEntity<>(sqlString, headers);
        String url = String.format("%s/RcvRptDoc/Create", apiUrlProperties.getApiUrl_prefix());
        System.out.println("配置:"+url);
        LogDto logDto = new LogDto();
        String json = String.format("{\"token\":\"%s\", \"sqlString\":\"%s\", \"apiUrlProperties\":\"%s\", \"restTemplate\":\"%s\"}",
                token, sqlString, apiUrlProperties, restTemplate);
        logDto.setParams(json);
        logDto.setDescription("executeRcvRptRequest");
        logDto.setLogType("Interface");

        logService.addLog(logDto);

        return restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class);
    }


    public static Date FIRST_REQUEST_TIME;
    public String getAuthorizeCode1(String clientid, String clientsecret) {
        String apiUrl = String.format("%s/OAuth2/GetAuthorizeCode", apiUrlProperties.getApiUrl_prefix());
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiUrl)
                .queryParam("clientid", clientid)
                .queryParam("clientsecret", clientsecret);
        AuthorizeCode authorizeCode = restTemplate.getForObject(builder.toUriString(), AuthorizeCode.class);
        return authorizeCode.getData();
    }
    @Override
    public String getAuthorizeCode(String clientid, String clientsecret)  {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("User-Agent", "PostmanRuntime/7.29.2");
        String apiUrl = String.format("%s/OAuth2/GetAuthorizeCode", apiUrlProperties.getApiUrl_prefix());
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiUrl)
                .queryParam("clientid", clientid)
                .queryParam("clientsecret", clientsecret);
        HttpEntity<String> requestEntity = new HttpEntity<>( headers);
        ResponseEntity<Map> responseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, requestEntity, Map.class);
//        ObjectMapper objectMapper = new ObjectMapper();
         return responseEntity.getBody().get("Data").toString();
    }

    @Override
    public void getLoginCode(String userCode, String entcode, String orgcode, String code) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("User-Agent", "PostmanRuntime/7.29.2");
        String apiUrl = String.format("%s/OAuth2/Login", apiUrlProperties.getApiUrl_prefix());
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiUrl)
                .queryParam("userCode", userCode)
                .queryParam("entcode", entcode)
                .queryParam("orgcode", orgcode)
                .queryParam("code", code);
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);
        ResponseEntity<Map> responseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, requestEntity, Map.class);
//        System.out.println(">>>>>:"+responseEntity.getBody().get("Data").toString());
        //        ObjectMapper objectMapper = new ObjectMapper();
        //        String returnString = objectMapper.readValue(responseEntity.getBody().get("Data").toString(), String.class);
        FIRST_REQUEST_TIME = new Date(System.currentTimeMillis());
        TOKEN=responseEntity.getBody().get("Data").toString();
    }


    public void getLoginCode1(String userCode, String entcode, String orgcode, String code) {
        String apiUrl = String.format("%s/OAuth2/Login", apiUrlProperties.getApiUrl_prefix());
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiUrl)
                .queryParam("userCode", userCode)
                .queryParam("entcode", entcode)
                .queryParam("orgcode", orgcode)
                .queryParam("code", code);
        AuthorizeCode authorizeCode = restTemplate.getForObject(builder.toUriString(), AuthorizeCode.class);
        TOKEN = authorizeCode.getData();
        FIRST_REQUEST_TIME = new Date(System.currentTimeMillis());
    }
    
    /**
     * 获取项目立项信息
     * @param token
     * @param sqlString
     * @throws Exception
     */
    @Override
    public void getProjectInfo(String token, String sqlString) throws Exception {
        ResponseEntity<Map> responseEntity = executeHttpRequest(token, sqlString, apiUrlProperties, restTemplate);
        if (responseEntity.getBody().get("Success").toString()!="true")
        {
            String errorData=responseEntity.getBody().get("Data").toString();
            errorReportService.addErrorReport2(null, null, null, "接口异常",
                    EXCEPTION_PRIORITY, HANDING_MAN, new Date(System.currentTimeMillis()), errorData,
                    null, null, null, null, null);
            throw new Exception(errorData);
        }
        List<Map> returnMap = (List<Map>) responseEntity.getBody().get("Data");
        Info info;
        Customer customer;
        for(Map<String, Object> map : returnMap){
            info = new Info();
//            [{customername=null, customercode=null, customersite=null, customerlinkman=null, so=, soitem=, sooperatorcode=33, projectname=巴彦县智慧水务项目, projectcode=GC0221013, projectmanager=, cabinetqty=, deliverydate=9999-12-31T00:00:00, orgcode=1002201130000355},
            info.setCustomerName(String.valueOf(map.get("customername")));
            info.setCustomerCode(String.valueOf(map.get("customercode")) );
            info.setCustomerAddress(String.valueOf(map.get("customersite")));
            info.setContactName(String.valueOf(map.get("customerlinkman")));
            info.setSo(String.valueOf(map.get("so")));
            info.setSoitem(String.valueOf(map.get("soitem")));
            info.setSooperatorCode(String.valueOf(map.get("projectcode")));
//            System.out.println("项目编号1:"+String.valueOf(map.get("projectcode")));
            System.out.println("项目编号2:"+(map.get("projectcode")==null?"":map.get("projectcode").toString()));
            if (StringUtils.isNotBlank(String.valueOf(map.get("projectname"))) && StringUtils.isNotBlank(String.valueOf(map.get("projectcode"))))
            {
                info.setProjectName(String.valueOf(map.get("projectname")));
                info.setProjectCode(String.valueOf(map.get("projectcode")));
            }
            else {
                continue;
            }

            info.setProjectManager(String.valueOf(map.get("projectmanager")));

            if (StringUtils.isNotBlank(String.valueOf(map.get("cabinetqty"))))
                info.setCabinetQty((int)map.get("cabinetqty"));
            else {
                info.setCabinetQty(1);
//                System.out.println("项目编号:"+String.valueOf(map.get("projectcode"))+"数量为空");
//                continue;
            }
            if (StringUtils.isNotBlank(String.valueOf(map.get("deliverydate"))))
            {
                String deliveryDate = (String) map.get("deliverydate");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                Date date;
                date = dateFormat.parse(deliveryDate);
                info.setDeliveryDate(date);
            }

            //组织名称
            info.setOrgCode(String.valueOf(map.get("orgcode")));
            //截取客户信息
            if(String.valueOf(map.get("customercode")).length() > 50){
                info.setCustomerCode(String.valueOf(map.get("customercode")).substring(0, 50));
            }
            if(String.valueOf(map.get("customerlinkman")).length() > 50){
                info.setContactName(String.valueOf(map.get("customerlinkman")).substring(0, 50));
            }
            //插入t_basedata_customer
            if (StringUtils.isNotBlank(info.getCustomerCode())) {
                customer = new Customer();
                customer.setCustomerCode(info.getCustomerCode());
                customer.setCustomerName(info.getContactName());
                customer.setCustomerSite(info.getCustomerAddress());
                customer.setCustomerLinkman(info.getContactName());
                Customer checkCustomer = customerRepository.findCustomerByCustomerCode(customer.getCustomerCode());
                if (checkCustomer == null) {
                    customerRepository.save(customer);
                }
            }
            //查询项目是否存在
            System.out.println("项目信息:"+info.getProjectCode());
            if(infoService.existsProjectCode(info.getProjectCode())){
                //查询项目管理员是否存在 && 权限为ROLE_ProjectManger
                if(!(infoService.existsProjectManger(info.getProjectManager()) && infoService.existsUserRole(info.getProjectManager()))) {
                    //抛异常给系统管理员
                    errorReportService.addErrorReport2(null, null, null, "接口异常",
                            EXCEPTION_PRIORITY, HANDING_MAN, new Date(System.currentTimeMillis()), "没有该用户或没有权限",
                            null, null, null, info.getProjectName(), null);
                    throw new Exception("没有该用户或没有权限");
                }
                System.out.println("项目信息:更新操作"+info.getProjectCode());
                    //获取原来的值+赋值+插入
                    Info oldInfo = infoService.getProjectInfos(info.getProjectCode());
                    BeanUtils.copyProperties(info, oldInfo);
                    infoService.insertProjectInfo(oldInfo);
            }else {
                System.out.println("项目信息:更新插入"+info.getProjectCode());
                //项目不存在，直接插入
                infoService.insertProjectInfo(info);
            }
        }
    }

    /**
     * 生产订单信息查询
     * @param token
     * @param sqlString
     */
    @Override
    public void getProductOrderInfo(String token, String sqlString) throws Exception {
        ResponseEntity<Map> responseEntity = executeHttpRequest(token, sqlString, apiUrlProperties, restTemplate);
        if (responseEntity.getBody().get("Success").toString()!="true")
        {
            String errorData=responseEntity.getBody().get("Data").toString();
            errorReportService.addErrorReport2(null, null, null, "接口异常",
                    EXCEPTION_PRIORITY, HANDING_MAN, new Date(System.currentTimeMillis()), errorData,
                    null, null, null, null, null);
            throw new Exception(errorData);
        }
        List<Map> returnMap = (List<Map>) responseEntity.getBody().get("Data");
        ProductOrderInfo productOrderInfo;
        for(Map<String, Object> map : returnMap){
            productOrderInfo = new ProductOrderInfo();
            productOrderInfo.setMaterialCode(String.valueOf(map.get("materialcode")));
            productOrderInfo.setErpMo(String.valueOf(map.get("mo")));
            String so = String.valueOf(map.get("so"));
            String soitem = String.valueOf(map.get("soitem"));
            String orgCode = String.valueOf(map.get("orgcode"));
            String projectCode = String.valueOf(map.get("projectcode"));

            int qty = (int)map.get("qty");
            MaterialInfo materialInfo = materialInfoService.getMaterialInfo(productOrderInfo.getMaterialCode());
            //根据项目编码查询info表
            Info info = infoService.getInfoByProjectCode(projectCode);
            if(info == null){
                errorReportService.addErrorReport2(null, null, null, "接口异常",
                        EXCEPTION_PRIORITY, HANDING_MAN, new Date(System.currentTimeMillis()), "该项目不存在",
                        null, null, null, info.getProjectName(), null);
                throw new Exception("该项目不存在");
            }
            //根据物料编码查询material表
            if(materialInfo == null){
                errorReportService.addErrorReport2(null, null, null, "接口异常",
                        EXCEPTION_PRIORITY, HANDING_MAN, new Date(System.currentTimeMillis()), "该物料不存在",
                        null, null, null, info.getProjectName(), null);
                throw new Exception("该物料不存在");
            } else{
                if(info.getSo() != so){
                    info.setSo(so);
                }
                if(info.getSoitem() != soitem){
                    info.setSoitem(soitem);
                }
                if(info.getOrgCode() != orgCode){
                    info.setOrgCode(orgCode);
                }
                if(info.getCabinetQty() != qty){
                    errorReportService.addErrorReport2(null, null, null, "接口异常",
                            EXCEPTION_PRIORITY, HANDING_MAN, new Date(System.currentTimeMillis()), "柜体数量不一致",
                            null, null, null, info.getProjectName(), null);
                    throw new Exception("柜体数量不一致");
                }
                infoService.insertProjectInfo(info);
            }
            List<ProductOrderInfo> productOrderInfoList = productOrderInfoService.getProduceOrderInfo(productOrderInfo.getMaterialCode(), productOrderInfo.getProjectCode());
            if(productOrderInfoList.isEmpty()){
                productOrderInfoService.insertProductOrderInfo(productOrderInfo);
            }
            for(ProductOrderInfo product : productOrderInfoList){
                product.setErpMo(productOrderInfo.getErpMo());
                productOrderInfoService.insertProductOrderInfo(product);
            }
        }
    }

    /**
     * 物料基础信息查询
     * @param token
     * @param sqlString
     */
    @Override
    public void getMaterialBasicInfo(String token, String sqlString) throws Exception {
        ResponseEntity<Map> responseEntity = executeHttpRequest(token, sqlString, apiUrlProperties, restTemplate);
        if (responseEntity.getBody().get("Success").toString()!="true")
        {
            String errorData=responseEntity.getBody().get("Data").toString();
            errorReportService.addErrorReport2(null, null, null, "接口异常",
                    EXCEPTION_PRIORITY, HANDING_MAN, new Date(System.currentTimeMillis()), errorData,
                    null, null, null, null, null);
            throw new Exception(errorData);
        }
        List<Map> returnMap = (List<Map>) responseEntity.getBody().get("Data");
        MaterialInfo materialInfo;
        for(Map<String, Object> map : returnMap){
            String materialProperty = String.valueOf(map.get("materialproperty"));
            if(!MATERIAL_PROPERTY.contains(materialProperty)){
                continue;
            }
            materialInfo = new MaterialInfo();
            materialInfo.setMaterialCode(String.valueOf(map.get("materialcode")));
            materialInfo.setMaterialName(String.valueOf(map.get("materialname")));
            materialInfo.setMaterialSpec(String.valueOf(map.get("materialspec")));
            materialInfo.setPara(String.valueOf(map.get("para")));
            materialInfo.setUnit(String.valueOf(map.get("unit")));
            materialInfo.setCategory(String.valueOf( map.get("category")));
            materialInfo.setBarCode(String.valueOf(map.get("barcode")));
            materialInfo.setBrand(String.valueOf(map.get("brand")));
            materialInfo.setEffective((int)map.get("effective"));
            materialInfo.setMaterialProperty(String.valueOf(map.get("materialproperty")));

            MaterialInfo oldInfo = materialInfoService.getMaterialInfo(materialInfo.getMaterialCode());
            if(oldInfo == null){
                materialInfoService.insertMaterialInfo(materialInfo);
            }
            BeanUtils.copyProperties(materialInfo, oldInfo);
            materialInfoService.insertMaterialInfo(oldInfo);
        }
    }

    /**
     * 采购订单信息查询
     * @param token
     * @param sqlString
     */
    @Override
    public void getPurchaseOrderInfo(String token, String sqlString) throws Exception {
        ResponseEntity<Map> responseEntity = executeHttpRequest(token, sqlString, apiUrlProperties, restTemplate);
        if (responseEntity.getBody().get("Success").toString()!="true")
        {
            String errorData=responseEntity.getBody().get("Data").toString();
            errorReportService.addErrorReport2(null, null, null, "接口异常",
                    EXCEPTION_PRIORITY, HANDING_MAN, new Date(System.currentTimeMillis()), errorData,
                    null, null, null, null, null);
            throw new Exception(errorData);
        }
        List<Map> returnMap = (List<Map>) responseEntity.getBody().get("Data");
        PurchaseOrderInfo purchaseOrderInfo;
        for(Map<String, Object> map : returnMap) {
            purchaseOrderInfo = new PurchaseOrderInfo();
            purchaseOrderInfo.setPo(String.valueOf(map.get("po")));
            purchaseOrderInfo.setPoItem(String.valueOf(map.get("poitem")));
            String materialName = String.valueOf(map.get("materialname"));
            if(materialName.length() > 50){
                purchaseOrderInfo.setPoItem(String.valueOf(map.get("materialname")).substring(0, 50));
            }
            purchaseOrderInfo.setMaterialName(String.valueOf(map.get("materialname")));
            purchaseOrderInfo.setMaterialCode(String.valueOf(map.get("materialcode")));
            purchaseOrderInfo.setPurchaser(String.valueOf(map.get("brand")));
            purchaseOrderInfo.setPurchaser(String.valueOf(map.get("puchaser")));

            if (StringUtils.isNotBlank(String.valueOf(map.get("planqty"))))
                purchaseOrderInfo.setPlanQty((float)map.get("planqty"));
            else {
                purchaseOrderInfo.setPlanQty(1);
            }
//            purchaseOrderInfo.setPlanQty((float) map.get("planqty"));

            if (StringUtils.isNotBlank(String.valueOf(map.get("planarriveddate"))))
            {
                String deliveryDate = (String) map.get("planarriveddate");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                Date date;
                date = dateFormat.parse(deliveryDate);
                purchaseOrderInfo.setPlanArrivedDate(date);
            }
            purchaseOrderInfo.setPlanArrivedDate((Date) map.get("planarriveddate"));

            if (StringUtils.isNotBlank(String.valueOf(map.get("actualarriveddate"))))
            {
                String deliveryDate = (String) map.get("actualarriveddate");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                Date date;
                date = dateFormat.parse(deliveryDate);
                purchaseOrderInfo.setActualArrivedDate(date);
            }
            purchaseOrderInfo.setActualArrivedDate((Date) map.get("actualarriveddate"));
            purchaseOrderInfo.setProjecCode(String.valueOf(map.get("projeccode")));

            if (StringUtils.isNotBlank(String.valueOf(map.get("ReceivedQty"))))
                purchaseOrderInfo.setReceivedQty((float)map.get("ReceivedQty"));
            else {
                purchaseOrderInfo.setReceivedQty(1);
            }
//            purchaseOrderInfo.setReceivedQty((float) map.get("ReceivedQty"));
            Info info = infoService.getInfoByProjectCode(purchaseOrderInfo.getProjecCode());
            if(info == null){
                errorReportService.addErrorReport2(null, null, null, "接口异常",
                        EXCEPTION_PRIORITY, HANDING_MAN, new Date(System.currentTimeMillis()), "该项目不存在",
                        null, null, null, info.getProjectName(), null);
                throw new Exception("该项目不存在");
            }
            //根据物料编码查询material表
            MaterialInfo materialInfo = materialInfoService.getMaterialInfo(purchaseOrderInfo.getMaterialCode());
            if(materialInfo == null){
                errorReportService.addErrorReport2(null, null, null, "接口异常",
                        EXCEPTION_PRIORITY, HANDING_MAN, new Date(System.currentTimeMillis()), "该物料不存在",
                        null, null, null, info.getProjectName(), null);
                throw new Exception("该物料不存在");
            }
            PurchaseOrderInfo oldInfo = purchaseOrderInfoService.getPurchaseOrderInfo(purchaseOrderInfo.getPo(),
                    purchaseOrderInfo.getPoItem());
            if(oldInfo == null){
                purchaseOrderInfoService.insertPurchaseOrderInfo(purchaseOrderInfo);
            }
            BeanUtils.copyProperties(purchaseOrderInfo, oldInfo);
            purchaseOrderInfoService.insertPurchaseOrderInfo(oldInfo);
        }
    }

    public void creatProductIssue() throws JSONException {
        //接受前端的参数，进行数据库的操作
        //构建请求体格式
        JSONObject issueBody = new JSONObject();
        JSONObject docType = new JSONObject();
        docType.put("Code", "");
        JSONArray mosArray = new JSONArray();
        JSONObject mosObj = new JSONObject();
        mosObj.put("Code", "");
        mosArray.put(mosObj);
        issueBody.put("DocType", docType);
        issueBody.put("Mos", mosArray);
        String jsonBody = issueBody.toString();

        //调用接口

        //处理响应
        
    }

    @Override
    public boolean checkTime(Date date) {
        if(FIRST_REQUEST_TIME==null || (date.getTime() - FIRST_REQUEST_TIME.getTime()) > 3 * 60 * 1000){
            return true;
        }
        return false;
    }
}
